//
//  ShowImageViewController.m
//  口袋
//
//  Created by dllo on 15/5/25.
//  Copyright (c) 2015年 口袋. All rights reserved.
//

#import "ShowImageViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "SANetWorkingTask.h"
#import "ShowImageModel.h"
#import "CommentViewController.h"
#import "AppDelegate.h"
#import "WeiboSDK.h"
#import "DKNightVersion.h"

#define kAppKey @"1286675123"
#define kRedirectURI @"https://api.weibo.com/oauth2/default.html"

#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
@interface ShowImageViewController ()<UIScrollViewDelegate>

@property (nonatomic, retain) NSString * note;

@property (nonatomic, retain) UILabel * pageLabel;

@property (nonatomic, retain) UILabel * titleLabel;

@property (nonatomic, retain) UILabel * noteLabel;

@end

@implementation ShowImageViewController
- (void)dealloc
{
    [_note release];
    [_replayCount release];
    [_setname release];
    [_skipID release];
    [_imageArray release];
    [_array release];
    [_scroll release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
        self.imageArray = [NSMutableArray array];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor blackColor]];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.barTintColor = [UIColor clearColor];
    //self.navigationController.navigationBar.tintColor = [UIColor redColor];
    //self.navigationController.navigationBar.backgroundColor = [UIColor blackColor];
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];

    


    // 数据解析
//    NSArray *arrayCount = [self.skipID componentsSeparatedByString:@"|"];
//    if (<#condition#>) {
//        <#statements#>
//    }
    NSString *skipid = [self.skipID substringFromIndex:4];
    
   // NSArray *idArray = [self.skipID componentsSeparatedByString:@"I"];//i
    //NSString *str = [idArray lastObject];
    NSArray *idArray2 = [skipid componentsSeparatedByString:@"|"]; // |
    NSString *id1 = [idArray2 firstObject];
    NSString *id2 = [idArray2 lastObject];

    NSString *url = [NSString stringWithFormat:@"http://c.m.163.com/photo/api/set/%@/%@.json", id1, id2];
    NSLog(@"url = %@", url);
    [SANetWorkingTask request:url parmater:nil block:^(NSDictionary *result) {
        self.boardid = [result objectForKey:@"boardid"];
        self.postid = [result objectForKey:@"postid"];
        NSArray *array = [result objectForKey:@"photos"];
        self.setname = [result objectForKey:@"setname"];
        for (NSDictionary *dic in array) {
            ShowImageModel *model = [[ShowImageModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.imageArray addObject:[dic objectForKey:@"imgurl"]];
            [self.array addObject:model];
        }
        [self createScroll];
       // [self createTitleLabel];
        [self createImageView];
        
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBarTintColor:[UIColor blackColor]];
    self.navigationController.navigationBar.nightBarTintColor = UIColorFromRGB(0x343434);
}

- (void)createScroll
{

    self.scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 49)];
    [self.scroll setContentSize:CGSizeMake(self.imageArray.count * self.view.frame.size.width, 0)];
    [self.scroll setBackgroundColor:[UIColor blackColor]];
    self.scroll.pagingEnabled = YES;
    self.scroll.delegate = self;
    [self.view addSubview:self.scroll];
    [self.scroll release];
    
    //评论按钮
    if (self.number != 5) {
        NSString *count = [NSString stringWithFormat:@"%@跟帖", self.replayCount];
        
        UIBarButtonItem *comments = [[UIBarButtonItem alloc]initWithTitle:count style:UIBarButtonItemStylePlain target:self action:@selector(commentAction)];
        [self.navigationItem setRightBarButtonItem:comments];
        [comments release];
    }
    
    
//    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 20, 50, 30)];
//    [button setImage:[UIImage imageNamed:@"return.png"] forState:UIControlStateNormal];
//    [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
//   // [button setBackgroundColor:[UIColor orangeColor]];
//    [self.view addSubview:button];
//    [button release];
}
#pragma mark -跳到评论界面
- (void)commentAction
{
    CommentViewController *comment = [[CommentViewController alloc]init];
    comment.type = self.boardid;
    comment.docID = self.postid;
    [self.navigationController pushViewController:comment animated:YES];
    [comment release];
}

- (void)createImageView
{
    for (int i = 0; i < self.imageArray.count; i++) {
        UIScrollView * subScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(_scroll.frame.size.width * i, 0, _scroll.frame.size.width, _scroll.frame.size.height)];
        
        subScroll.minimumZoomScale = 0.5;
        subScroll.maximumZoomScale = 3;
        subScroll.delegate = self;
        
        NSURL *url = [NSURL URLWithString:[self.imageArray objectAtIndex:i]];
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0.15 * HEIGHT, self.scroll.frame.size.width, HEIGHT * 0.36 )];
        [imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"loadingBlack.jpg"]completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            imageView.frame = CGRectMake(0, 0, imageView.frame.size.width,image.size.height/image.size.width * imageView.frame.size.width);
            imageView.center = CGPointMake(WIDTH / 2, (HEIGHT - 64 - 49 - 30) / 2);
        }];
        
        [subScroll addSubview:imageView];
//        [self.scroll addSubview:imageView];
        [imageView release];
        
//        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0.024 * WIDTH + i * WIDTH, 0.63 * HEIGHT, WIDTH - (0.026 * WIDTH) * 2, HEIGHT * 0.37)];
//        [view setBackgroundColor:[UIColor clearColor]];
        [self.scroll addSubview:subScroll];

    }
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0.03 * WIDTH, HEIGHT * 0.62, WIDTH - (0.026 * WIDTH) * 2, 0.08 * WIDTH)];
    _titleLabel.text = self.setname;
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.font = [UIFont boldSystemFontOfSize:19];
    [self.view addSubview:_titleLabel];
    [_titleLabel release];
    
    self.pageLabel = [[UILabel alloc]initWithFrame:CGRectMake(0.85 * WIDTH, HEIGHT * 0.62, 0.2 * WIDTH, 0.08 * WIDTH)];
            NSString *page = [NSString stringWithFormat:@"1/%lu", (unsigned long)self.imageArray.count];
            _pageLabel.text = page;
    _pageLabel.textColor = [UIColor whiteColor];
    _pageLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_pageLabel];
    [_pageLabel release];
    
    
    ShowImageModel *model = [self.array objectAtIndex:0];
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:16]};
    CGRect rect = [model.note boundingRectWithSize:CGSizeMake(WIDTH - (0.026 * WIDTH) * 2, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    
    UIScrollView *noteScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0.03 * WIDTH, HEIGHT * 0.66, WIDTH - (0.03 * WIDTH) * 2, 0.16 * HEIGHT)];
    [noteScroll setBackgroundColor:[UIColor clearColor]];
    noteScroll.contentSize = CGSizeMake(0, rect.size.height);
    self.noteLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, noteScroll.frame.size.width, rect.size.height)];
//    if (i == 0) {
        _noteLabel.text = model.note;
//    }
    if (self.note.length == 0) {
        self.note = model.note;
    }
    _noteLabel.numberOfLines = 0;
    _noteLabel.textColor = [UIColor whiteColor];
    _noteLabel.font = [UIFont systemFontOfSize:15];
    [noteScroll addSubview:_noteLabel];
    
    UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(WIDTH / 6 * 5.2, HEIGHT - 64 - 40, WIDTH / 10, WIDTH / 10)];
    [button setImage:[UIImage imageNamed:@"shareBlack.png"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"shareWhite.png"] forState:UIControlStateHighlighted];
    [button addTarget:self action:@selector(buttonActt) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:noteScroll];
    [self.view addSubview:button];
    //        [subScroll addSubview:view];
//    [self.scroll addSubview:view];
    [_noteLabel release];
    [noteScroll release];
//    [view release];
    

}

#pragma mark -ScrollView协议

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return [scrollView.subviews objectAtIndex:0];
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView NS_AVAILABLE_IOS(3_2)
{

}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView.frame.size.width != WIDTH) {
    } else {
        NSInteger num1 = scrollView.contentOffset.x / WIDTH + 1;
        NSString *page = [NSString stringWithFormat:@"%ld/%lu", (long)num1, self.imageArray.count];
        _pageLabel.text = page;
        
        ShowImageModel *model = [self.array objectAtIndex:num1 - 1];
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:16]};
        CGRect rect = [model.note boundingRectWithSize:CGSizeMake(WIDTH - (0.026 * WIDTH) * 2, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        
//        self.noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH, rect.size.height)];
        self.noteLabel.frame = CGRectMake(0, 0, WIDTH * 0.94, rect.size.height);
        _noteLabel.numberOfLines = 0;
        _noteLabel.text = model.note;
    }
}

#pragma mark -点击分享按钮事件
- (void)buttonActt
{
    
    AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    authRequest.redirectURI = kRedirectURI;
    authRequest.scope = @"all";
    
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:[self messageToShare] authInfo:authRequest access_token:myDelegate.wbtoken];
    //    request.shouldOpenWeiboAppInstallPageIfNotInstalled = NO;
    [WeiboSDK sendRequest:request];
    
}

- (WBMessageObject *)messageToShare
{
    NSString * title = self.setname;
    
    NSString * all = [title stringByAppendingString:self.note];
    
    if (all.length >= 140) {
        all = [all substringToIndex:139];
    }
    
    WBMessageObject *message = [WBMessageObject message];
    
    message.text = NSLocalizedString(all, nil);
    
    WBImageObject *image = [WBImageObject object];
    image.imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Welcome" ofType:@"jpg"]];
    message.imageObject = image;
    
    return message;
}

- (void)buttonAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
    NSLog(@"返回成功");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
